﻿module InkType.ViewModel.Xml

open System
open System.Collections.Generic
open System.Xml.Linq


type XAttr =
    | XAttr of name : string * value : string

module XAttrs =
    let rec tryGet name attrs =
        match attrs with
        | XAttr (name', value') :: attrs' when name' = name -> Some value'
        | _ :: attrs' -> tryGet name attrs'
        | [] -> None


type XElem =
    | XElem of name : string * attrbutes : XAttr list * children : XElem list

type XDoc =
    | XDoc of root : XElem


let XmlSave filename xdoc =
    let toXAttr (XAttr (name, value)) =
        new XAttribute (XName.Get name, value)

    let rec toXElem (XElem (name, attrs, children)) : XElement =
        let e = new XElement (XName.Get name)
        attrs |> List.iter (fun attr -> e.Add (toXAttr attr))
        children |> List.iter (fun child -> e.Add (toXElem child))
        e

    let toXDoc (XDoc root) =
        new XDocument (new XDeclaration ("1.0", "Unicode", null), box (toXElem root))

    (toXDoc xdoc).Save (filename : string)


let XmlLoad filename =
    let asXAttr (attr : XAttribute) =
        XAttr (attr.Name.ToString (), attr.Value)

    let rec asXElem (elem : XElement) =
        XElem (
            elem.Name.ToString (),
            elem.Attributes () |> Seq.map asXAttr |> List.ofSeq,
            elem.Elements () |> Seq.map asXElem |> List.ofSeq)

    let asXDoc (doc : XDocument) =
        XDoc (asXElem doc.Root)

    XDocument.Load (filename : string)
    |> asXDoc


